// wait_group 实现有条件的等待
#include <workflow/WFFacilities.h>
#include <workflow/WFTaskFactory.h>
#include <workflow/HttpMessage.h>
#include <workflow/HttpUtil.h>
#include <iostream>
#include <signal.h>
using std::cout;
using std::cerr;
static WFFacilities::WaitGroup waitGroup(1);
void handler(int signum){
    cout << "done\n";
    waitGroup.done();
}
void httpCallback(WFHttpTask *httpTask){ 
    protocol::HttpRequest *req = httpTask->get_req(); // 获取请求
	protocol::HttpResponse *resp = httpTask->get_resp(); // 获取响应

	int state = httpTask->get_state(); // 获取状态
	int error = httpTask->get_error(); // 获取错误原因
	switch (state){
	case WFT_STATE_SYS_ERROR:
		cerr <<"system error: " << strerror(error) << "\n";
		break;
	case WFT_STATE_DNS_ERROR:
		cerr <<"DNS error: "  << gai_strerror(error) << "\n";
		break;
	case WFT_STATE_SSL_ERROR:
		cerr <<"SSL error\n";
		break;
	case WFT_STATE_TASK_ERROR:
		cerr <<"Task error\n";
		break;
	case WFT_STATE_SUCCESS:
		break;
	}
	if (state != WFT_STATE_SUCCESS){
		cerr <<"Failed. Press Ctrl-C to exit.\n";
		return;
	}
	
	const void *body;
	size_t body_len;
	resp->get_parsed_body(&body, &body_len); // get_parsed_body找到响应报文的报文体
    //cerr << static_cast<const char *>(body) << "\n";

	WFRedisTask * nextTask = WFTaskFactory::create_redis_task(
		"redis://127.0.0.1:6379",10,nullptr
	);
	nextTask->get_req()->set_request("SET",{"www.taobao.com",static_cast<const char *>(body)});
	series_of(httpTask)->push_back(nextTask);
}
int main(){
    signal(SIGINT,handler); // 注册信号
    // 用户调用工厂函数去创建一个任务
    WFHttpTask * httpTask =  WFTaskFactory::create_http_task(
        "http://www.taobao.com",
        10,
        10,
        httpCallback
    );
	// 找到请求
	protocol::HttpRequest *req = httpTask->get_req();
    // 用户把任务交给框架
    httpTask->start();
    // 用户就等待
    waitGroup.wait();
    cout << "finish!\n";
}
